<?php
// 本类由系统自动生成，仅供测试用途
class IndexAction extends Action {
    public function index(){
               try{

            $redis = RedisQueueService::getInstance();
        }catch (\Exception $e) {
            var_dump($e->getMessage());
        }

        $a = $redis->pull('styy_print');
        // var_dump(123);
        // var_dump($a);
        // echo 8082;exit;
    }

    public function getPrint(){
    	$url = 'http://127.0.0.1:81/Restaurantstyy/ZduRestaurantApi/getorder';
    	$data = $this->curlToGet($url);
    	if($data['code'] ==200){
    		$redis = RedisQueueService::getInstance();
    		$redis->push('styy_print',$data['data']);
    	}
    }

    public function addPrint(){
    	//var_dump(phpinfo());die;
    	$data = $GLOBALS['HTTP_RAW_POST_DATA'];
    	import("@.ORG.RedisService");
    	$post = json_decode($data,true);
        $order = json_decode($post['print'],true);
        //实例化redis服务


        $redis = RedisQueueService::getInstance();
        $hotGoods = array();
        $coldGoods = array();
        $waterGoods = array();
        if(count($order)==0){
        	$this->ajaxReturn(array('code' => 10086,'message' => '数据为空','data'=>array()));
        }
    	foreach ($order['goods_list'] as $k => $v) {
    		if($v['print_type'] ==1){
            	$hotGoods[] = $v;
            }elseif ($v['print_type'] ==2){
                $coldGoods[] = $v;
            }elseif ($v['print_type'] ==3){
                $waterGoods[] = $v;
            }
    	}
    	$printInfo = array('order_sn'=>$order['order_sn'],'order_num'=>$order['order_num'],'order_amount'=>$order['order_amount'],'pay_type'=>$order['pay_type'],'restaurant'=>$order['restaurant'],
            'push_time'=>time(),'hot_list'=>$hotGoods,'cold_list'=>$coldGoods,'water_list'=>$waterGoods);
        $redis->push('styy_print',$printInfo);
    	$this->ajaxReturn(array('code' => 200,'message' => '请求成功','data'=>array()));
    }

    public function test(){
    	$redis = RedisQueueService::getInstance();
		$data = $redis->pull('styy_print');
		cprint($data);
    }
	
	/**
	 *定时的在队列中获取打印信息
	 */
	 public function toPrint(){
	 	//热打印机
			/*$service_port = 9100;
			$address = '192.168.1.111' ;
			$content = 556;
			$this->Send_socket_connect($service_port,$address, $content,$type='hot_list');
			die;*/
		$redis = RedisQueueService::getInstance();
		$data = $redis->pull('styy_print');
		if(!$data){
			return true;
		}
		var_dump($data);
		if($data['pay_type'] == 1){
				$payType = '微信';
		}
		if($data['pay_type'] == 2){
			$payType = '支付宝';
		}
		if($data['pay_type'] == 4){
			$payType = '一卡通';
		}
		if($data['pay_type'] == 5||6){
			$payType = '校园卡';
		}
		if(count($data['hot_list'])>0){
			//热打印机
			$service_port = 9100;
			$address = '192.168.52.168' ;
			$content = $this->content($data,$payType,$type='hot_list');
			//print_r($content);die;
			$this->Send_socket_connect($service_port,$address, $content,$type='hot_list');
		}
		if(count($data['cold_list'])>0){
			//冷打印机
			$service_port = 9100;
			$address = '192.168.52.168';
			$content = $this->content($data,$payType,$type='cold_list');
			$this->Send_socket_connect($service_port,$address, $content,$type='cold_list');
		}
		if(count($data['water_list'])>0){
			//饮料打印机
			$service_port = 9100;
			$address = '192.168.52.168';
			$this->Send_socket_connect($service_port,$address, $content,$type='water_list');
		}
	 }
	 
	 /*
	  *拼接数据
	  */
	  private function content($data,$payType,$type){
			$htotal = 0;
			$hstr = '';
			foreach($data[$type] as $hk=>$hv){
				$hstr .= str_pad($hv['goods_name'],36,'　').' '. str_pad($hv['goods_num'],16,'　').'￥'.number_format($hv['goods_num']*$hv['goods_price'],2)  . "\x0D\x0A" . "\x0D\x0A";
                $htotal += $hv['goods_num']*$hv['goods_price'];
			}
			$content =
			"\x1B\x21\x08\x1B\x21\x10".'              ' . $data['restaurant'] . "\x0A\x0A".
			'餐号：' . $data['order_num'] . "\x0A".' '."\x0A".
			"\x1B\x21\x00".'订单编号：' . $data['order_sn'] . "\x0A".' '."\x0A" .
			'打印时间:' .date("Y-m-d H:i:s"). "\x0A".' '."\x0A" .
			'支付方式:'. $payType . "\x0A".' '."\x0A" .
			'------------------------------------------------' . "\x0A".' '."\x0A" .
			"\x1B\x21\x08\x1B\x21\x10".str_pad('商品名称',36,'　').str_pad('数量',15).'小计'."\x0A".' '."\x0A" .$hstr ."\x0A".
			'------------------------------------------------' .
			"\x0A".'总计：' . $htotal .'元'.' '."\x0A".' '."\x0A"."\x1B\x21\x08\x1B\x21\x10".'              '.'青橄榄网络技术支持'.' '."\x0A".'  '."\x0A\x1D\x56\x01";
			/*$content =
			'================================' ."\x0D\x0A ".
			"\x1B\x21\x10".'餐厅名：' . $data['restaurant'] . "\x0D\x0A".
			'餐号：' . $data['order_num'] . "\x0D\x0A" .
			'订单编号：' . $data['order_sn'] . "\x0D\x0A" .
			'打印时间:'. date('Y-m-d H:i:s') . "\x0D\x0A" .
			'支付方式:'. $payType . "\x0D\x0A" .
			'------------------------' . "\x0D\x0A" .
			str_pad('商品名称',18,' ').str_pad('数量',12).'小计'."\x0D\x0A" .$hstr ."\x0D\x0A" .
			'------------------------' . "\x0D\x0A" .
			'总计：' . $htotal .'元'. "\x0D\x0A". "\x0D\x0A". "\x0D\x0A". "\x0D\x0A". "\x0D\x0A";
			str_pad('商品名称',24,' ').str_pad('数量',14).'小计'."\x0A".' '."\x0A" .$hstr ."\x0A".*/
			return $content;
	  }
	 
	 /**
	 *本地打印
	 *
	 */
	 public function Send_socket_connect($service_port,$address, $in,$type) {
	//创建 TCP/IP socket$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("could not create socket!");
		$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("could not create socket!");
		//设置超时时间
		$timeout = 2;
		$time = time();
		//设置非阻塞模式
		// @socket_set_nonblock($socket);
		/*$comand="\x1D\x56\x01\x48";
		$in=$in.$comand;*/

		$in = mb_convert_encoding($in, "GBK", "UTF-8");

		//超时判断
		while (!@socket_connect($socket, $address, $service_port)) {
			$err = socket_last_error($socket);
			// 连接成功，跳出循环
			if ($err === 10056) {
				break;
			}
			//连接失败，判断超时时间，停止
			if ((time() - $time) >= $timeout) {
				socket_close($socket);
				print('网络异常，请检查网络连接！！');
				$redis = RedisQueueService::getInstance();
				if($type =='hot_list'){
					$redis->push('zy_print',$data,$pushType='tail');
				}
				if($type =='cold_list'){
					//删除热菜后，再次入队列
					$data['hot_list'] = array();
					$redis->push('zy_print',$data,$pushType='tail');
				}
				if($type =='water_list'){

					//删除热冷菜，再次入队列
					$data['hot_list'] = array();
					$data['cold_list'] = array();
					$redis->push('zy_print',$data,$pushType='tail');
				}
				exit();
			}
			// 刷新频率（250毫秒）
			usleep(250000);
		}
		//设置阻塞模式
		@socket_set_block($socket);
		//发送命令到设备
		socket_write($socket, $in, strlen($in));
		//关闭连接
		//关闭连接
		socket_close($socket);
	}



	public function runAll(){
		set_time_limit(0);
		while (1) {
		$this->getPrint();
		$this->toPrint();
		sleep(1);
		}
	}

	/*
     * curlGet请求
     */
    public function curlToGet($url){
        //初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
		
		//打印获得的数据
        //释放curl句柄
        curl_close($ch);

        return json_decode($output,true);
    }

        public function test2(){
    	$sGoods = Service('RestaurantStyy/BaseOrder');
    	$return=$sGoods->haveWestAndDeal('399');
    	if($return){
    		echo '1';
    	}else{
    		echo '2';
    	}
    }
}
